package com.rush.manageepac.controller;

import com.rush.manageepac.util.FileUtil;
import com.rush.manageepac.vo.R;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/api/file/")
public class FileController {

    @PostMapping("uploadimg.do")
    public R upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //1.验证文件是否存在
        if(!file.isEmpty()){
            //2.获取上传文件名并完成重命名
            String fn= FileUtil.reName(file.getOriginalFilename());
            //3.获取上传的文件内容
            byte[] data=file.getBytes();
            //4.创建文件存储的文件夹
            File dir=new File(request.getServletContext().getRealPath("/upload"));
            if(!dir.exists()){
                dir.mkdirs();
            }
            //5.存储
            IOUtils.write(data,new FileOutputStream(new File(dir,fn)));
            //6.返回
            return R.ok("/upload/"+fn);
        }else {
            return R.fail();
        }
    }
}
